package com.hmall.item.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.dto.PageDTO;
import com.alibaba.fastjson.JSON;
import com.hmall.item.mapper.ItemMapper;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.ItemDoc;
import com.hmall.item.service.IItemService;
import com.hmall.item.utils.DateUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class ItemService extends ServiceImpl<ItemMapper, Item> implements IItemService {
    @Autowired
    private ItemMapper itemMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public PageDTO<Item> findPage(Long page, Long size) {
        PageDTO<Item> pageDTO = new PageDTO<>();
        Long start = (Long)(page-1)*size;
        List<Item> pages =  itemMapper.findPage(start,size);
        Long count = itemMapper.count();
        pageDTO.setTotal(count);
        pageDTO.setList(pages);
        return pageDTO;
    }

    @Override
    public void addItem(Item item) {
        int exist = itemMapper.exist(item.getId());
        if(exist!=1)
        {
            item.setStatus(2);
            item.setCreateTime(DateUtils.getNowDate());
            item.setUpdateTime(DateUtils.getNowDate());
            int i = itemMapper.addItem(item);
        }
    }

    @Override
    public void updateStatus(Long id, Long sta) {
        itemMapper.updateStatus(id,sta);
        Item item = itemMapper.selectById(id);
        String queueName = "my.queue";
        String result = JSON.toJSONString(item);
        rabbitTemplate.convertAndSend(queueName, result);
    }

    @Override
    public boolean updateById(Item item) {
        int exist = itemMapper.exist(item.getId());
        if(exist==1)
        {
            item.setUpdateTime(DateUtils.getNowDate());
            int i = itemMapper.updateById(item);
            if(i==1){
                return true;
            }
            else {
                return false;
            }
        }
        return false;
    }

    @Override
    public void deleteById(Long id) {
        Item item = itemMapper.selectById(id);
        if(item.getStatus()==2){
            itemMapper.deleteById(id);
        }else {
            throw new RuntimeException();
        }
    }
}
